package com.jxb.test;

import java.util.LinkedList;
import java.util.Random;

/**
 *滑动窗口算法
 */
public class SlidingTimeWindow {

    private static LinkedList<Long> slots = new LinkedList<>();//存储滑动窗口的格子,设置10个格子，每个格子100ms，对1秒钟的pqs进行限流
    private static Long Counters = 0L;//计数器
    private static Long qpsLimit = 100L;//限流阈值

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    doCheck();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //模拟请求访问
        while (true) {
            Counters++;
            Thread.sleep(new Random().nextInt(15));
        }
    }

    public static boolean doCheck() throws InterruptedException {
        while (true) {
            slots.addLast(Counters);
            if (slots.size() > 10) {
                slots.remove();
            }
            //判断当前时间窗口的qps是否大于100
            if (slots.peekLast() - slots.peekFirst() > qpsLimit) {
                System.out.println("进行限流... ...");

            }else {
                System.out.println("通过... ...");
            }
            Thread.sleep(100);
        }
    }

}
